﻿//////////////////////////////////////////////////////////////////////////////
//
// Copyright © 1998-2024 Glodon Company Limited.
//
// Licensed under the MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the “Software”),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//////////////////////////////////////////////////////////////////////////////
#include "IAddinManager.h"
#include "GbmpFileSystem.h"
#include "IApplicationEventArgs.h"

#include <QtCore/QDir>
#include "UiConfiguration.h"
#include "GDFoundation/IExtension.h"

#include "GbmpFileSystem.h"
#include <QtCore/QResource>

const wchar_t* TR_MODULE_NAME = L"exComponentsUiAdapter";
using namespace gcmp;
namespace Sample
{
    namespace
    {
        //图标资源文件路径
        QString GetAppResourceFile() {
            return QString::fromStdWString(FileSystem::GetExeDirPath()) + "Gdmp.resources.dll";
        }
    }

    class UiSetupExtension :public gdmp::IExtension
    {
    public:
        void On(gcmp::IApplicationEventArgs* pArgs) override;
    private:
        std::vector<std::wstring> FindAllUiConfigurationFiles();
    };

    void UiSetupExtension::On(gcmp::IApplicationEventArgs* pArgs)
    {
        if (pArgs && pArgs->GetType() == gcmp::ApplicationEventType::Executed) {
            {//加载资源文件
                QResource::registerResource(GetAppResourceFile());
            }
            //从界面配置文件加载界面，注意界面元素定义可能存在于不同文件
            //需要先构造UiConfiguration（加载界面定义）
            //然后SetupUi（创建真实的界面）
            std::vector<gcmp::OwnerPtr<UiConfiguration>> extensions;

            std::vector<std::wstring> files = FindAllUiConfigurationFiles();
            for (auto& file : files)
            {
                extensions.emplace_back(NEW_AS_OWNER_PTR(UiConfiguration, file));
            }
            for (auto& extension : extensions)
            {
                if (extension) {
                    extension->SetupUi();
                }
            }
        }
        if (pArgs && pArgs->GetType() == gcmp::ApplicationEventType::Closed)
        {
            //卸载资源文件
            QResource::unregisterResource(GetAppResourceFile());
        }
    }

    std::vector<std::wstring> UiSetupExtension::FindAllUiConfigurationFiles()
    {
        //从插件目录扫描所有.ui.xml文件
        std::vector<std::wstring> directories{};
        IAddinManager* pAddinManager = IAddinManager::Get();
        if (pAddinManager) {
            directories.push_back(
                FileSystem::GetExeDirPath() + L"/" + pAddinManager->GetAddinConfigDirectory()
            );
            std::set<std::wstring> items = pAddinManager->GetExternalAddinConfigDirectories();
            for (auto& item : items) {
                directories.push_back(item);
            }
        }

        {//!!!这里的路径仅作为公共组件内部测试使用，参考该代码时请忽略或移除相关代码
            std::wstring path = FileSystem::GetExeDirPath() + L"/AppGdmp_plugin_config";
            if (QDir(QString::fromStdWString(path)).exists()) {
                directories.push_back(path);
            }
        }

        std::vector<std::wstring> files{};
        for (auto& path : directories) {
            QDir dir(QString::fromStdWString(path));
            QStringList list = dir.entryList(QStringList("*.ui.xml"));
            for (auto& file : list) {
                QString filepath = dir.absoluteFilePath(file);
                files.emplace_back(filepath.toStdWString());
            }
        }
        return files;
    }

    gdmp::IExtensionStub stubs[]{
        gdmp::IExtension::Register<UiSetupExtension>()
    };
}
